﻿namespace EyeOpen.Presentation
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data.Common;
    using EyeOpen.Data;
    using EyeOpen.Domain;

    public abstract class ObjectDataSourceHelper<T> : IServiceProvider<T> where T : IUniqueObject
    {
        private IDataMapper<T> dataMapper;

        public abstract string ConnectionString
        {
            get;
        }

        public abstract string TableName
        {
            get;
        }

        public abstract string ProviderName
        {
            get;
        }

        private IDataMapper<T> DataMapper
        {
            get
            {
                if (this.dataMapper == null)
                {
                    DbProviderFactory factory = DbProviderFactories.GetFactory(this.ProviderName);
                    this.dataMapper = new DataMapper<T>(this.ConnectionString, factory, this.TableName);
                }

                return this.dataMapper;
            }
        }

        [DataObjectMethod(DataObjectMethodType.Select, false)]
        public T Get(Guid id)
        {
            if (id.Equals(Guid.Empty))
            {
                return default(T);
            }

            return this.DataMapper.Get(id);
        }

        [DataObjectMethod(DataObjectMethodType.Select, true)]
        public virtual IList<T> GetAll()
        {
            return this.DataMapper.GetAll();
        }

        [DataObjectMethod(DataObjectMethodType.Insert, true)]
        public virtual void Insert(T value)
        {
            if (value.Id == null)
            {
                value.Id = Guid.NewGuid();
            }

            this.DataMapper.Insert(value);
        }

        [DataObjectMethod(DataObjectMethodType.Update, true)]
        public virtual void Update(T value)
        {
            this.DataMapper.Update(value);
        }

        [DataObjectMethod(DataObjectMethodType.Delete, true)]
        public virtual void Delete(T value)
        {
            this.DataMapper.Delete(value);
        }
   }
}